package cool.doudou.doudada.iot.codec.core.listener;

import cool.doudou.doudada.iot.codec.core.factory.MethodFactory;
import cool.doudou.doudada.iot.codec.core.method.BundleStateChangeMethod;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.osgi.framework.BundleContext;

import java.lang.reflect.Method;

/**
 * Bundle监听器
 *
 * @author jiangcs
 * @since 2022/09/30
 */
@Slf4j
@AllArgsConstructor
public class BundleListener {
    public static void init(BundleContext bundleContext) {
        bundleContext.addBundleListener(bundleEvent -> {
            log.info("bundleEvent: {}", bundleEvent);

            BundleStateChangeMethod bundleStateChangeMethod = MethodFactory.get();
            if (bundleStateChangeMethod != null) {
                Method method = bundleStateChangeMethod.getMethod();
                Object bean = bundleStateChangeMethod.getBean();
                try {
                    method.invoke(bean, bundleEvent.getBundle());
                } catch (Exception e) {
                    log.error("bean[{}].method[{}] invoke exception: ", bean, method.getName(), e);
                }
            } else {
                log.warn("bundleStateChangeMethod not found");
            }
        });
    }
}
